package com.nsharmon.iBridge.beans;

import java.lang.reflect.Constructor;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;

import javax.persistence.EntityManager;

import com.nsharmon.iBridge.dao.EMF;

public abstract class CollectionBean<T> {
	private final Class<T> classT;
	private List<T> list = new ArrayList<T>();
	private T selected = null;
	protected Logger logger = Logger.getAnonymousLogger();
	
	public CollectionBean(Class<T> classOfT) {
		this.classT = classOfT;
		
		refreshCollection();
	}
	
	protected void refreshCollection() {
		list = loadCollection();
	}

	protected abstract List<T> loadCollection();

	public T getSelected() {
		return selected;
	}
	
	public List<T> getObjects() {
		if(list == null) {
			refreshCollection();
		}
		return list;
	}
	
	public void newObject() {
		selected = null;
		try {
			Constructor<T> constr = classT.getConstructor((Class<?>[])null);
			selected = constr.newInstance((Object[])null);
		} catch (Exception e) {
			logger.log(Level.SEVERE, "Could not create object '" + classT.getSimpleName() + "'!  It must have default constructor!", e);
			selected = null;
		} 
	}
	
	public void selectObject(T object) {
		selected = null;
		if(list.contains(object)) {
			selected = object;
		}
	}
	
	public void selectObject(int index) {
		selectObject(list.get(index));
	}	
	
	public void addSelected() {
		if(selected != null) {
			EntityManager entityManager = EMF.createEntityManager();
			
			try {
				entityManager.persist(selected);
				if(!list.contains(selected)) {
					list.add(selected);
				}
			} finally {
				entityManager.close();
			}
		}
	}
	
	public void removeSelected() {
		if(selected != null) {
			EntityManager entityManager = EMF.createEntityManager();
			
			try {
				if(list.contains(selected)) {
					entityManager.remove(selected);					
					list.remove(selected);
				}
				selected = null;				
			} finally {
				entityManager.close();
			}
		}		
	}
}
